<template>
  <div class="layout-container">
    <div class="layout-container-form flex space-between">
      <div class="layout-container-form-handle">
        <el-button type="primary" :icon="Plus" @click="handleAdd">{{ $t('message.common.add') }}</el-button>
        <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel(chooseData)">
          <template #reference>
            <el-button type="danger" :icon="Delete" v-permission="['超级管理员']" :disabled="chooseData.length === 0">{{ $t('message.common.delBat')
            }}</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm icon="" confirm-button-text="通过" cancel-button-text="不通过" confirm-button-type="success" cancel-button-type="danger" @confirm="handleAudit(chooseData, 1)" @cancel="handleAudit(chooseData, 2)">
          <template #reference>
            <el-button type="warning" :icon="Checked" v-permission="['超级管理员', '总经理']" :disabled="chooseData.length === 0">{{
          $t('message.common.audit')
        }}</el-button>
          </template>
        </el-popconfirm>
      </div>
      <div class="layout-container-form-search">
        <el-select v-model="query.userName" clearable placeholder="请选择报备人">
          <el-option v-for="item in userSelectData" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <!-- <el-input v-model="query.keyWord" :placeholder="$t('message.common.searchTip')"
          @change="getTableData(true)"></el-input> -->
        <el-button type="primary" :icon="Search" class="search-btn" @click="getTableData(true)">{{
          $t('message.common.search') }}</el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showIndex="true" :showSelection="true" :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
        <el-table-column prop="auditStatusName" label="审核状态" align="center" />
        <el-table-column prop="userTrueName" label="报备人" align="center" />
        <el-table-column prop="startDate" label="开始时间" align="center" >
          <template #default="scope">
            {{ convertTime(scope.row.startDate)}}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束时间" align="center" >
          <template #default="scope">
            {{ convertTime(scope.row.endDate)}}
          </template>
        </el-table-column>
        <el-table-column prop="requestTypeName" label="报备类型" align="center" />
        <el-table-column prop="requestTime" label="报备时间" align="center" >
          <template #default="scope">
            {{ convertDate(scope.row.requestTime)}}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column :label="$t('message.common.handle')" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)">{{ $t('message.common.update') }}</el-button>
            <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel([scope.row])">
              <template #reference>
                <el-button type="danger" v-permission="['超级管理员']">{{ $t('message.common.del') }}</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </Table>
      <Layer :layer="layer" @getTableData="getTableData" v-if="layer.show" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, reactive } from 'vue'
import Table from '@/components/table/index.vue'
import { Page } from '@/components/table/type'
import { getData, del, audit } from '@/api/attendance/request'
import Layer from './layer.vue'
import { ElMessage } from 'element-plus'
import type { LayerInterface } from '@/components/layer/index.vue'
import { Plus, Search, Delete, Checked } from '@element-plus/icons'
import { userData, requestTypeData, auditData } from './enum'
import Permission from '@/directive/permission'
export default defineComponent({
  name: 'crudTable',
  components: {
    Table,
    Layer
  },
  directives: {
    Permission
  },
  setup() {
    // 计算属性基本使用
    const convertDate = computed(() => (date: Date) => {
      if (!date) return ''
      // var newDate=/\d{4}\/\d{1,2}\/\d{1,2}/g.exec(new Date(date).toLocaleString())??[]
      var date = new Date(date);
      // 回调函数必须return，结果就是计算的结果
      // 如果计算属性依赖的数据发生变化，那么会重新计算
      return [date.getFullYear(), date.getMonth()+1, date.getDate()].join('/')
    })
    const convertTime = computed(() => (date: Date) => {
      if (!date) return ''
      // 回调函数必须return，结果就是计算的结果
      // 如果计算属性依赖的数据发生变化，那么会重新计算
      return new Date(date).toLocaleString()
    })
    // 存储搜索用的数据
    const query = reactive({
      userName: ''
    })

    // 弹窗控制器
    const layer: LayerInterface = reactive({
      show: false,
      title: '新增',
      showButton: true
    })
    // 分页参数, 供table使用
    const page: Page = reactive({
      index: 1,
      size: 20,
      total: 0
    })
    const loading = ref(true)
    const tableData = ref([])
    const chooseData = ref([])
    const userSelectData = ref([])
    const handleSelectionChange = (val: []) => {
      chooseData.value = val
    }
    // 获取表格数据
    // params <init> Boolean ，默认为false，用于判断是否需要初始化分页
    const getTableData = (init: boolean) => {
      loading.value = true
      if (init) {
        page.index = 1
      }
      let params = {
        pageIndex: page.index,
        pageSize: page.size,
        ...query
      }
      getData(params)
        .then(res => {
          let data = res.data.list
          if (Array.isArray(data)) {
            data.forEach(d => {
              const requestType = requestTypeData.find(r => r.value === d.requestType)
              requestType ? d.requestTypeName = requestType.label : d.requestType
              const user = userData.find(u => u.value === d.userName)
              user ? d.userTrueName = user.label : d.userName
              const audit = auditData.find(o => o.value === d.auditStatus)
              audit ? d.auditStatusName = audit.label : d.auditStatus
            })
          }
          userSelectData.value = userData
          tableData.value = data
          page.total = res.data.total.value
        })
        .catch(error => {
          tableData.value = []
          page.index = 1
          page.total = 0
        })
        .finally(() => {
          loading.value = false
        })
    }
    // 删除功能
    const handleDel = (data: object[]) => {
      let params = {
        ids: data.map((e: any) => {
          return e.id
        })
      }
      del(params.ids)
        .then(res => {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData(tableData.value.length === 1 ? true : false)
        })
    }
    const handleAudit = (data: object[], auditStatus: any) => {
      let params = {
        auditStatus: auditStatus,
        ids: data.map((e: any) => {
          return e.id
        })
      }
      audit(params)
        .then(res => {
          ElMessage({
            type: 'success',
            message: '审核成功'
          })
          getTableData(tableData.value.length === 1 ? true : false)
        })
    }
    // 新增弹窗功能
    const handleAdd = () => {
      layer.title = '新增数据'
      layer.show = true
      delete layer.row
    }
    // 编辑弹窗功能
    const handleEdit = (row: object) => {
      layer.title = '编辑数据'
      layer.row = row
      layer.show = true
    }
    getTableData(true)
    return {
      Plus,
      Search,
      Delete,
      Checked,
      query,
      tableData,
      chooseData,
      userSelectData,
      loading,
      page,
      layer,
      handleSelectionChange,
      handleAdd,
      handleEdit,
      handleDel,
      handleAudit,
      getTableData,
      convertDate,
      convertTime
    }
  }
})
</script>

<style lang="scss" scoped></style>